package com.financing.wap.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.common.Pager;
import com.financing.wap.dao.IAccountDao;
import com.financing.wap.dao.IActivitesDao;
import com.financing.wap.dao.IActivitieGiftDao;
import com.financing.wap.dto.AccountCorpDTO;
import com.financing.wap.dto.AccountDetailDTO;
import com.financing.wap.dto.ActivitesDTO;
import com.financing.wap.dto.ActivitieGiftDTO;
import com.financing.wap.dto.ActivitiesWeChatGiftDTO;
import com.financing.wap.service.IActivitieGiftService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.vo.ActivitieGiftVo;

/**
 * 
 * @ClassName: ActivitieGiftServiceImpl
 * @Description: 活动礼品 
 * @author  qiye
 * @date 2014年11月4日 上午10:23:39
 *
 */
@Service("activitieGiftServiceImpl")
public class ActivitieGiftServiceImpl implements IActivitieGiftService {
	
	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IActivitieGiftDao activitieGiftDaoImpl;
	
	@Autowired
	private IAccountDao accountDao;
	
	@Autowired
	private IActivitesDao activitesDao;

	@Override
	public List<ActivitieGiftVo> queryActivitieGiftDTOList(ActivitieGiftDTO activitieGiftDTO,Pager pager) {
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("activitieGiftDTO", activitieGiftDTO);
		param.put("pager", pager);
		return activitieGiftDaoImpl.queryActivitieGiftList(param);
	}

	@Override
	public Integer countActivitiesGift(String faId) {
		return activitieGiftDaoImpl.countActivitiesGift(faId);
	}

	@Override
	public Integer ActivitiesGiftJobExecution(String activitiesCode,String aStatus,Integer count) throws Exception{
		
		Map<String,Object>  map = new HashMap<String,Object>()	;
		map.put("aStatus", aStatus);
		map.put("activiesCode", activitiesCode);
		map.put("count", count);
		
		List<ActivitieGiftDTO> list = activitieGiftDaoImpl.queryActivitieGiftListForJob(map);
		for(ActivitieGiftDTO dto : list){
			
			//礼品金额
			BigDecimal aAmount = dto.getaAmount();
			
			//更新注册人用户信息
			AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(dto.getFaUserId());
			
			if(accountDto == null){
				logger.warn("ActivitiesGiftJobExecution getFaAccountByUserId is null ActivitieGifid:"+dto.getId());
				continue;
			}
			//添加注册人账户明细
			AccountDetailDTO accountDetailDTO = new AccountDetailDTO();
			accountDetailDTO.setAccountId(accountDto.getId());
			accountDetailDTO.setAmount(aAmount.negate());
			accountDetailDTO.setUserId(accountDto.getUserId());
			accountDetailDTO.setRemark("红包失效");
			accountDetailDTO.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_OUTPUT); //：出账
			accountDetailDTO.setOperateType(Constants.P_ACCOUNT_OPERATE_RED_FAILURE);//操作类型： 08红包失效
			accountDetailDTO.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
			accountDetailDTO.setActivitieGiftId(dto.getId());  //来源Id (礼品id)
			DTOdateSetUtil.setUpdateInfo(accountDetailDTO);
			DTOdateSetUtil.setCreateInfo(accountDetailDTO);
			accountDao.addUserAccountDetail(accountDetailDTO);
			
			//修改红包状态为失效
			dto.setaStatus("03");
			DTOdateSetUtil.setUpdateInfo(dto);
			activitieGiftDaoImpl.updateActivitieGift(dto);
			
			//更新账户信息
			accountDto.setAccountBalance(accountDto.getAccountBalance().subtract(aAmount)); //余额-红包金额
			accountDto.setAllAccount(accountDto.getAllAccount());//总累计收入 -不变
			accountDto.setAccountBalanceSleep(accountDto.getAccountBalanceSleep().subtract(aAmount));//冻结余额-红包金额
			accountDto.setAccountBalanceActivity(accountDto.getAccountBalanceActivity()); //可提现金额-不变
			DTOdateSetUtil.setUpdateInfo(accountDto);
			accountDao.updateAccountBalanceActivity(accountDto);
		}
		int exCount = list.size();
		logger.info("ActivitiesGiftJobExecution 执行数 size:"+exCount);
		return exCount;
	}
	@Override
	public Integer ActivitiesGiftJobExecutionForSpecialTreatment(String activitiesCode,String aStatus,Integer count) throws Exception{
		
		Map<String,Object>  map = new HashMap<String,Object>()	;
		map.put("aStatus", aStatus);
		map.put("activiesCode", activitiesCode);
		map.put("count", count);
		
		List<ActivitieGiftDTO> list = activitieGiftDaoImpl.queryActivitieGiftListForJob(map);
		for(ActivitieGiftDTO dto : list){
			
			//红包88特殊处理 -领取时间与当前时间比较 超过3个月属于失效
			//判断时间是否超过3个月  
			if(DateUtil.dateAddmonthForSystem(dto.getCreateDate(),3)){
				logger.warn("ActivitiesGiftJobExecution dateAddmonthForSystem true  ActivitieGifid:"+dto.getId());
				continue;
			}
			
			//礼品金额
			BigDecimal aAmount = dto.getaAmount();
			
			//更新注册人用户信息
			AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(dto.getFaUserId());
			
			if(accountDto == null){
				logger.warn("ActivitiesGiftJobExecution getFaAccountByUserId is null ActivitieGifid:"+dto.getId());
				continue;
			}
			//添加注册人账户明细
			AccountDetailDTO accountDetailDTO = new AccountDetailDTO();
			accountDetailDTO.setAccountId(accountDto.getId());
			accountDetailDTO.setAmount(aAmount.negate());
			accountDetailDTO.setUserId(accountDto.getUserId());
			accountDetailDTO.setRemark("红包失效");
			accountDetailDTO.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_OUTPUT); //：出账
			accountDetailDTO.setOperateType(Constants.P_ACCOUNT_OPERATE_RED_FAILURE);//操作类型： 08红包失效
			accountDetailDTO.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
			accountDetailDTO.setActivitieGiftId(dto.getId());  //来源Id (礼品id)
			DTOdateSetUtil.setUpdateInfo(accountDetailDTO);
			DTOdateSetUtil.setCreateInfo(accountDetailDTO);
			accountDao.addUserAccountDetail(accountDetailDTO);
			
			//修改红包状态为失效
			dto.setaStatus("03");
			DTOdateSetUtil.setUpdateInfo(dto);
			activitieGiftDaoImpl.updateActivitieGift(dto);
			
			//更新账户信息
			accountDto.setAccountBalance(accountDto.getAccountBalance().subtract(aAmount)); //余额-红包金额
			accountDto.setAllAccount(accountDto.getAllAccount());//总累计收入 -不变
			accountDto.setAccountBalanceSleep(accountDto.getAccountBalanceSleep().subtract(aAmount));//冻结余额-红包金额
			accountDto.setAccountBalanceActivity(accountDto.getAccountBalanceActivity()); //可提现金额-不变
			DTOdateSetUtil.setUpdateInfo(accountDto);
			accountDao.updateAccountBalanceActivity(accountDto);
		}
		int exCount = list.size();
		logger.info("ActivitiesGiftJobExecution 执行数 size:"+exCount);
		return exCount;
	}

	@Override
	public BigDecimal mollionsWealthCount() throws Exception {
		return activitieGiftDaoImpl.mollionsWealthCount();
	}

	@Override
	public List<ActivitieGiftDTO> sendGift(ActivitieGiftDTO actgift) throws Exception {
		List<ActivitieGiftDTO> list = new ArrayList<ActivitieGiftDTO>();
//		BigDecimal totalAmount = new BigDecimal( new Random(System.currentTimeMillis()).nextInt(150)+50);
//		BigDecimal oneAmount = totalAmount.divide(new BigDecimal(6));
		//将总金额平均分为6分放入红包
		
		// 50、100、150、200之间的随机金额
		BigDecimal randomNo = new BigDecimal(new Random().nextInt(4) + 1 );// 1 2 3 4
		BigDecimal firstAmount = randomNo.multiply(new BigDecimal(2));// 固定首份红包
		int shareHongBao = randomNo.intValue() * 5;// 红包分享个数
		BigDecimal oneAmount = new BigDecimal(9.6);//除去固定金额后的每份红包金额
		actgift.setaAmount(oneAmount);
		
		for(int i = 0 ;i < shareHongBao;i++){
			ActivitieGiftDTO tmp = new ActivitieGiftDTO();
		     tmp = (ActivitieGiftDTO) actgift.clone();
			activitieGiftDaoImpl.insertActivitieGift(actgift);
			list.add(tmp);
		}
		actgift.setaAmount(firstAmount);
		actgift.setaStatus("02");// 固定首份红包为已使用过状态
		int activitieId = activitieGiftDaoImpl.insertActivitieGift(actgift);
		AccountCorpDTO accountDto =  accountDao.getFaAccountByUserId(actgift.getFaUserId());
		//添加注册人账户明细
		AccountDetailDTO accountDetailDTO = new AccountDetailDTO();
		accountDetailDTO.setAccountId(accountDto.getId());
		accountDetailDTO.setAmount(actgift.getaAmount());
		accountDetailDTO.setUserId(accountDto.getUserId());
		accountDetailDTO.setRemark("红包失效");
		accountDetailDTO.setAccountType(Constants.P_ACCOUNT_DETAIL_TYPE_OUTPUT); //：出账
		accountDetailDTO.setOperateType(Constants.P_ACCOUNT_OPERATE_RED_FAILURE);//操作类型： 08红包失效
		accountDetailDTO.setOperateStatus(Constants.P_ACCOUNT_OPERATE_STATUS_SUCCESS);
		accountDetailDTO.setActivitieGiftId(activitieId);  //来源Id (礼品id)
		DTOdateSetUtil.setUpdateInfo(accountDetailDTO);
		DTOdateSetUtil.setCreateInfo(accountDetailDTO);
		accountDao.addUserAccountDetail(accountDetailDTO);
		
		accountDto.setAccountBalance(accountDto.getAccountBalance().add(actgift.getaAmount()));  
		accountDto.setAccountBalanceSleep((accountDto.getAccountBalanceSleep().add(actgift.getaAmount())));
		accountDto.setAllAccount(accountDto.getAllAccount().add(actgift.getaAmount()));
		
		DTOdateSetUtil.setUpdateInfo(accountDto);
		accountDao.updateAccountBalanceActivity(accountDto);
		
//		//修改目前已经发放的总金额
//		ActivitesDTO dto = new ActivitesDTO();
//		dto.setActiviesCode("SDHD");
//		dto.setActiviesNowAmount(actgift.getaAmount());
//		activitesDao.updateActivitesByCode(dto);
		list.add(actgift);
		return list;
	}

	@Override
	public List<ActivitieGiftDTO> queryGifts(ActivitieGiftDTO actgift) throws Exception {
		return activitieGiftDaoImpl.queryActivitiesHBGift(actgift);
	}
	
	@Override
	public int isActivitieEnd(String activitieCode){
		   int result = 0;
			ActivitesDTO act = activitesDao.searchActivitesByCode(activitieCode);
			Date startDate = act.getActiviesStartTime();
			Date endDate = act.getActiviesEndTime();
			Date currentDate = new Date();
			// 时间条件
			if(currentDate.before(startDate) || currentDate.after(endDate)){
				result = 1;
			}
			// 金额条件
			if(act.getActiviesTotalAmount().compareTo(act.getActiviesNowAmount() ) <= 0){
				result = 2;
			}
			return result;
	}

	@Override
	public List<Map<String, Object>> queryYLYXHDGifts(ActivitieGiftDTO actgift)
			throws Exception {
		return activitieGiftDaoImpl.queryYLYXHDGifts(actgift);
	}

	@Override
	public int addActivitiesWeChatGift(
			ActivitiesWeChatGiftDTO activitiesWeChatGiftDTO) throws Exception {
		return activitieGiftDaoImpl.addActivitiesWeChatGift(activitiesWeChatGiftDTO);
	}

	@Override
	public int updateActivitiesWeChatGift(
			ActivitiesWeChatGiftDTO activitiesWeChatGiftDTO) throws Exception {
		return activitieGiftDaoImpl.updateActivitiesWeChatGift(activitiesWeChatGiftDTO);
	}

	@Override
	public int updateActivitieGift(ActivitieGiftDTO dto) throws Exception{
		return activitieGiftDaoImpl.updateActivitieGift(dto);
	}
}
